<template>
  <div class="stepper">
    <div class="button" @click="decrement" :disabled="value <= min">
      <img src="../../assets/images/decrement.svg" alt="" v-if="theme === 'white'" /><img
        src="../../assets/images/decrement-black.svg"
        alt=""
        v-else
      />
    </div>
    <input
      type="number"
      v-model="value"
      @input="handleInput"
      :min="min"
      :max="max"
      :placeholder="placeholder"
    />
    <div class="button" @click="increment" :disabled="value >= max">
      <img src="../../assets/images/increment.svg" alt="" v-if="theme === 'white'" /><img
        src="../../assets/images/increment-black.svg"
        alt=""
        v-else
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Stepper',
  props: {
    value: {
      type: Number,
      default: 0,
    },
    min: {
      type: Number,
      default: 0,
    },
    max: {
      type: Number,
      default: Infinity,
    },
    canInput: {
      type: Boolean,
      default: true,
    },
    placeholder: {
      type: String,
      default: '请填入数量',
    },
    title: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      theme: window.getCssStyle(),
    };
  },
  methods: {
    increment() {
      if (this.value < this.max) {
        this.$emit('input', this.value + 1);
      } else {
        this.$toast(`${this.title}最大为${this.max}`);
      }
    },
    decrement() {
      if (this.value > this.min) {
        this.$emit('input', this.value - 1);
      } else {
        this.$toast(`${this.title}最小为${this.min}`);
      }
    },
    // 防止输入过大的数字
    handleInput(event) {
      const inputValue = event.target.value.trim(); // 去除首尾空格
      if (inputValue === '') {
        this.$emit('input', '');
        return;
      }
      let value = +inputValue; // 将输入值转换为数字
      if (isNaN(value)) {
        // 如果转换后不是数字，说明输入不合法，直接返回
        return;
      }
      // 根据输入值进行限制
      value = Math.min(Math.max(value, this.min), this.max);
      this.value = value;
      this.$emit('input', value); // 发送处理后的值给父组件
    },
  },
};
</script>

<style scoped>
.stepper {
  width: 148px;
  height: 38px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  font-family: PingFangSC-Regular;
  font-size: 15px;
  color: var(--text-1);
  text-align: center;
  line-height: 22px;
  font-weight: 400;
}

.button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 36px;
  height: 100%;
  cursor: pointer;
  background-color: var(--bg-color-4);
  font-weight: bold;
  img {
    width: 4vw;
    height: 4vw;
  }
}

input {
  width: 76px;
  height: 100%;
  text-align: center;
  color: var(--text-1);
  background-color: var(--bg-color-4);
  &::placeholder {
    color: var(--atom-color-text-quaternary);
  }
}
</style>
